from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, HttpResponseForbidden, JsonResponse
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Sum, Count
from django.utils import timezone
from .utils import has_permission, get_user_permissions, get_user_roles
from .models import Goods, Inbound, Outbound, Stock, Inventory, TaskRecord, WageRule
from .forms import GoodsForm, InboundForm, OutboundForm, InventoryForm, WageCalculationForm
from datetime import datetime


def api_test(request):
    """
    简单的API测试接口
    """
    data = {
        'status': 'success',
        'message': '仓库管理系统API测试接口',
        'user_authenticated': request.user.is_authenticated,
    }
    
    if request.user.is_authenticated:
        data['user'] = request.user.username
        data['permissions'] = get_user_permissions(request.user)
        data['roles'] = get_user_roles(request.user)
    
    return JsonResponse(data)


@login_required
def dashboard(request):
    """
    仓库管理系统主界面
    """
    # 测试数据库连接
    try:
        goods_count = Goods.objects.count()
        inbound_count = Inbound.objects.count()
        outbound_count = Outbound.objects.count()
        inventory_count = Inventory.objects.count()
        db_status = f"数据库连接正常，共有 {goods_count} 个商品，{inbound_count} 条入库记录，{outbound_count} 条出库记录，{inventory_count} 条盘点记录"
    except Exception as e:
        db_status = f"数据库连接异常: {str(e)}"
    
    # 获取仓库基础数据统计
    try:
        # 商品统计
        total_goods = Goods.objects.count()
        
        # 库存统计
        total_stock = Stock.objects.aggregate(total=Sum('quantity'))['total'] or 0
        
        # 今日入库统计
        today = timezone.now().date()
        today_inbound = Inbound.objects.filter(operation_time__date=today).aggregate(total=Sum('quantity'))['total'] or 0
        today_inbound_count = Inbound.objects.filter(operation_time__date=today).count()
        
        # 今日出库统计
        today_outbound = Outbound.objects.filter(operation_time__date=today).aggregate(total=Sum('quantity'))['total'] or 0
        today_outbound_count = Outbound.objects.filter(operation_time__date=today).count()
        
        # 最近操作记录
        recent_operations = []
        
        # 最近入库记录
        recent_inbounds = Inbound.objects.select_related('goods', 'operator').order_by('-operation_time')[:5]
        for inbound in recent_inbounds:
            recent_operations.append({
                'type': '入库',
                'goods': inbound.goods.name,
                'quantity': inbound.quantity,
                'operator': inbound.operator.username,
                'time': inbound.operation_time
            })
        
        # 最近出库记录
        recent_outbounds = Outbound.objects.select_related('goods', 'operator').order_by('-operation_time')[:5]
        for outbound in recent_outbounds:
            recent_operations.append({
                'type': '出库',
                'goods': outbound.goods.name,
                'quantity': outbound.quantity,
                'operator': outbound.operator.username,
                'time': outbound.operation_time
            })
        
        # 按时间排序操作记录
        recent_operations.sort(key=lambda x: x['time'], reverse=True)
        recent_operations = recent_operations[:5]  # 只取最近5条
        
    except Exception as e:
        total_goods = 0
        total_stock = 0
        today_inbound = 0
        today_inbound_count = 0
        today_outbound = 0
        today_outbound_count = 0
        recent_operations = []
    
    context = {
        'user_permissions': get_user_permissions(request.user),
        'user_roles': get_user_roles(request.user),
        'db_status': db_status,
        'total_goods': total_goods,
        'total_stock': total_stock,
        'today_inbound': today_inbound,
        'today_inbound_count': today_inbound_count,
        'today_outbound': today_outbound,
        'today_outbound_count': today_outbound_count,
        'recent_operations': recent_operations
    }
    return render(request, 'warehouse/dashboard.html', context)


@login_required
def goods_list(request):
    """
    商品列表页面 - 需要goods_read权限
    """
    if not has_permission(request.user, 'goods_read'):
        return HttpResponseForbidden("您没有查看商品的权限")
    
    # 获取商品列表
    try:
        goods_list = Goods.objects.all()
        db_status = "数据库连接正常"
    except Exception as e:
        goods_list = []
        db_status = f"数据库连接异常: {str(e)}"
    
    context = {
        'goods_list': goods_list,
        'user_permissions': get_user_permissions(request.user),
        'user_roles': get_user_roles(request.user),
        'db_status': db_status
    }
    return render(request, 'warehouse/goods_list.html', context)


@login_required
def goods_create(request):
    """
    创建商品页面 - 需要goods_create权限
    """
    if not has_permission(request.user, 'goods_create'):
        return HttpResponseForbidden("您没有创建商品的权限")
    
    if request.method == 'POST':
        form = GoodsForm(request.POST, user=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, '商品创建成功')
            return redirect('warehouse:goods_list')
    else:
        form = GoodsForm()
    
    context = {
        'form': form,
        'user_permissions': get_user_permissions(request.user),
        'user_roles': get_user_roles(request.user)
    }
    return render(request, 'warehouse/goods_create.html', context)


@login_required
def goods_detail(request, goods_id):
    """
    商品详情页面 - 需要goods_read权限
    """
    if not has_permission(request.user, 'goods_read'):
        return HttpResponseForbidden("您没有查看商品的权限")
    
    goods = get_object_or_404(Goods, id=goods_id)
    
    # 获取库存信息
    stocks = Stock.objects.filter(goods=goods)
    
    context = {
        'goods': goods,
        'stocks': stocks,
        'user_permissions': get_user_permissions(request.user),
        'user_roles': get_user_roles(request.user)
    }
    return render(request, 'warehouse/goods_detail.html', context)


@login_required
def goods_edit(request, goods_id):
    """
    编辑商品页面 - 需要goods_update权限
    """
    if not has_permission(request.user, 'goods_update'):
        return HttpResponseForbidden("您没有编辑商品的权限")
    
    goods = get_object_or_404(Goods, id=goods_id)
    
    if request.method == 'POST':
        form = GoodsForm(request.POST, instance=goods)
        if form.is_valid():
            form.save()
            messages.success(request, '商品信息更新成功')
            return redirect('warehouse:goods_detail', goods_id=goods.id)
    else:
        form = GoodsForm(instance=goods)
    
    context = {
        'form': form,
        'goods': goods,
        'user_permissions': get_user_permissions(request.user),
        'user_roles': get_user_roles(request.user)
    }
    return render(request, 'warehouse/goods_edit.html', context)


@login_required
def inbound_create(request):
    """
    创建入库记录 - 需要inbound_create权限
    """
    if not has_permission(request.user, 'inbound_create'):
        return HttpResponseForbidden("您没有创建入库记录的权限")
    
    if request.method == 'POST':
        form = InboundForm(request.POST, user=request.user)
        if form.is_valid():
            try:
                form.save()
                messages.success(request, '入库记录创建成功')
                return redirect('warehouse:inbound_list')
            except Exception as e:
                messages.error(request, f'入库失败: {str(e)}')
    else:
        form = InboundForm()
    
    context = {
        'form': form,
        'user_permissions': get_user_permissions(request.user),
        'user_roles': get_user_roles(request.user)
    }
    return render(request, 'warehouse/inbound_create.html', context)


@login_required
def inbound_list(request):
    """
    入库记录列表 - 需要goods_read权限
    """
    if not has_permission(request.user, 'goods_read'):
        return HttpResponseForbidden("您没有查看入库记录的权限")
    
    try:
        inbound_list = Inbound.objects.select_related('goods', 'operator').all().order_by('-operation_time')
        db_status = "数据库连接正常"
    except Exception as e:
        inbound_list = []
        db_status = f"数据库连接异常: {str(e)}"
    
    context = {
        'inbound_list': inbound_list,
        'user_permissions': get_user_permissions(request.user),
        'user_roles': get_user_roles(request.user),
        'db_status': db_status
    }
    return render(request, 'warehouse/inbound_list.html', context)


@login_required
def outbound_create(request):
    """
    创建出库记录 - 需要outbound_create权限
    """
    if not has_permission(request.user, 'outbound_create'):
        return HttpResponseForbidden("您没有创建出库记录的权限")
    
    if request.method == 'POST':
        form = OutboundForm(request.POST, user=request.user)
        if form.is_valid():
            try:
                form.save()
                messages.success(request, '出库记录创建成功')
                return redirect('warehouse:outbound_list')
            except Exception as e:
                messages.error(request, f'出库失败: {str(e)}')
    else:
        form = OutboundForm()
    
    context = {
        'form': form,
        'user_permissions': get_user_permissions(request.user),
        'user_roles': get_user_roles(request.user)
    }
    return render(request, 'warehouse/outbound_create.html', context)


@login_required
def outbound_list(request):
    """
    出库记录列表 - 需要goods_read权限
    """
    if not has_permission(request.user, 'goods_read'):
        return HttpResponseForbidden("您没有查看出库记录的权限")
    
    try:
        outbound_list = Outbound.objects.select_related('goods', 'operator', 'approver').all().order_by('-operation_time')
        db_status = "数据库连接正常"
    except Exception as e:
        outbound_list = []
        db_status = f"数据库连接异常: {str(e)}"
    
    context = {
        'outbound_list': outbound_list,
        'user_permissions': get_user_permissions(request.user),
        'user_roles': get_user_roles(request.user),
        'db_status': db_status
    }
    return render(request, 'warehouse/outbound_list.html', context)


@login_required
def inventory_create(request):
    """
    创建库存盘点记录 - 需要inventory_create权限
    """
    if not has_permission(request.user, 'inventory_create'):
        return HttpResponseForbidden("您没有创建盘点记录的权限")
    
    if request.method == 'POST':
        form = InventoryForm(request.POST, user=request.user)
        if form.is_valid():
            try:
                form.save()
                messages.success(request, '盘点记录创建成功')
                return redirect('warehouse:inventory_list')
            except Exception as e:
                messages.error(request, f'盘点失败: {str(e)}')
    else:
        form = InventoryForm()
    
    context = {
        'form': form,
        'user_permissions': get_user_permissions(request.user),
        'user_roles': get_user_roles(request.user)
    }
    return render(request, 'warehouse/inventory_create.html', context)


@login_required
def inventory_list(request):
    """
    库存盘点记录列表 - 需要goods_read权限
    """
    if not has_permission(request.user, 'goods_read'):
        return HttpResponseForbidden("您没有查看盘点记录的权限")
    
    try:
        inventory_list = Inventory.objects.select_related('goods', 'operator').all().order_by('-operation_time')
        db_status = "数据库连接正常"
    except Exception as e:
        inventory_list = []
        db_status = f"数据库连接异常: {str(e)}"
    
    context = {
        'inventory_list': inventory_list,
        'user_permissions': get_user_permissions(request.user),
        'user_roles': get_user_roles(request.user),
        'db_status': db_status
    }
    return render(request, 'warehouse/inventory_list.html', context)


@login_required
def wage_list(request):
    """
    工资列表 - 需要finance_read权限
    """
    if not has_permission(request.user, 'finance_read'):
        return HttpResponseForbidden("您没有查看工资信息的权限")
    
    # 获取所有工资记录
    try:
        task_records = TaskRecord.objects.select_related('user', 'goods').all().order_by('-operation_time')
        db_status = "数据库连接正常"
    except Exception as e:
        task_records = []
        db_status = f"数据库连接异常: {str(e)}"
    
    context = {
        'task_records': task_records,
        'user_permissions': get_user_permissions(request.user),
        'user_roles': get_user_roles(request.user),
        'db_status': db_status
    }
    return render(request, 'warehouse/wage_list.html', context)


@login_required
def wage_calculate(request):
    """
    工资计算 - 需要finance_manage权限
    """
    if not has_permission(request.user, 'finance_manage'):
        return HttpResponseForbidden("您没有计算工资的权限")
    
    if request.method == 'POST':
        form = WageCalculationForm(request.POST)
        if form.is_valid():
            start_date = form.cleaned_data['start_date']
            end_date = form.cleaned_data['end_date']
            
            # 计算工资
            wage_data = calculate_wages(start_date, end_date)
            
            context = {
                'form': form,
                'wage_data': wage_data,
                'start_date': start_date,
                'end_date': end_date,
                'user_permissions': get_user_permissions(request.user),
                'user_roles': get_user_roles(request.user)
            }
            return render(request, 'warehouse/wage_calculate.html', context)
    else:
        # 默认显示本月的工资计算
        today = timezone.now().date()
        start_date = today.replace(day=1)
        form = WageCalculationForm(initial={
            'start_date': start_date,
            'end_date': today
        })
    
    context = {
        'form': form,
        'user_permissions': get_user_permissions(request.user),
        'user_roles': get_user_roles(request.user)
    }
    return render(request, 'warehouse/wage_calculate.html', context)


def calculate_wages(start_date, end_date):
    """
    计算指定日期范围内的工资
    """
    # 获取任务记录统计
    task_stats = TaskRecord.objects.filter(
        operation_time__date__gte=start_date,
        operation_time__date__lte=end_date
    ).values('user__username', 'task_type').annotate(
        count=Count('id'),
        total_quantity=Sum('quantity')
    ).order_by('user__username', 'task_type')
    
    # 获取工资规则
    wage_rules = {}
    for rule in WageRule.objects.all():
        wage_rules[rule.task_type] = float(rule.unit_price)
    
    # 计算每个人的工资
    wage_data = {}
    for stat in task_stats:
        username = stat['user__username']
        task_type = stat['task_type']
        count = stat['count']
        total_quantity = stat['total_quantity'] or 0
        
        if username not in wage_data:
            wage_data[username] = {
                'username': username,
                'tasks': {},
                'total_wage': 0
            }
        
        unit_price = wage_rules.get(task_type, 0)
        wage = unit_price * total_quantity
        wage_data[username]['tasks'][task_type] = {
            'count': count,
            'total_quantity': total_quantity,
            'unit_price': unit_price,
            'wage': wage
        }
        wage_data[username]['total_wage'] += wage
    
    return wage_data